/**
 * Created with JetBrains WebStorm.
 * User: Administrator
 * Date: 14-7-14
 * Time: 下午9:07
 * To change this template use File | Settings | File Templates.
 */
/*
* 策略模式支持用户在运行时选择算法
* */

// ef: 表单验证问题
var validator = {

    // 所有可用的检查，公用的检查方法写在此处，还可以在需要时额外补充
    type: {
        isNonEmpty: {                                  // 验证数据不是空
            validator: function(value) {
                return value !== "";
            },
            instructor: "the value cannot be empty"
        },
        isNumber: {                                  // 验证数据只能是数字
            validator: function(value) {
                return !isNaN(value);
            },
            instructor: "the value can only be a valid number, e.g 1, 4.14 or 2010"
        },
        isAlphaNum: {                     // 验证数据只能是有数字和字母组成
            validator: function(value) {
                return !/^a-z0-9/i.test(value);
            },
            instructor: "the value can only contain characters and numbers, no special symbol"
        }
    },

    // 在当前验证会话中的错误信息
    message: [],

    // 当前验证的配置，在每次验证时配置此信息，数据名称：验证类型
    /*
     eg:
     validator.config = {
     first_name: 'isNoEmpty',
     age: 'isNumber',
     userName: 'isAlphaNum'
     }
     */
    config: {},

    // 接口方法，data为键值对的数据对象
    validate: function(data) {
        var i = null, type = null, checker = null, result_ok = null, msg = null;

        // 重置错误消息
        this.message = [];

        for(i in data) {
            if(data.hasOwnProperty(i)) {
                type = this.config[i];
                checker = this.type[type];

                if(!type) {
                    continue;  // 不需要验证
                }

                if(!checker) {
                    throw {
                        name: "ValidationError",
                        message: "No handle to validate type " + type
                    };
                }

                result_ok = checker.validator(data[i]);
                if(!result_ok) {
                    msg = "Invalid value for *" + i + "*, " + checker.instructor;
                    this.message.push(msg);
                }
            }
        }
        return this.hasErrors();
    },

    // 帮助程序
    hasErrors: function() {
        return this.message.length !== 0;
    }

};